package com.haonan.service.Impl;

import com.haonan.Utils.BCryptUtil;
import com.haonan.Utils.JwtUtils;
import com.haonan.mapper.EmpMapper;
import com.haonan.pojo.dto.LoginDTO;
import com.haonan.pojo.entily.Emp;
import com.haonan.pojo.vo.LoginVO;
import com.haonan.service.LoginService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class LoginServiceImpl implements LoginService {
    @Autowired
    private EmpMapper empMapper;

    /**
     * 登录认证
     * @param loginDTO
     * @return
     */
    @Override
    public LoginVO login(LoginDTO loginDTO) {
        LoginVO loginVO = new LoginVO();
        Emp e= empMapper.findByUsername(loginDTO.getUsername());
        if(e.getPassword()!=null&&BCryptUtil.verifyPassword(loginDTO.getPassword(),e.getPassword())){
            BeanUtils.copyProperties(e,loginVO);
            if(loginVO.getName()!=null && loginVO.getName()!=""){
                Map<String,Object> claims = new HashMap<>();
                claims.put("id",loginVO.getId());
                claims.put("username",loginVO.getUsername());
                String jwt = JwtUtils.generateJwt(claims);
                loginVO.setToken(jwt);
                return loginVO;
            }
        }

        return null;
    }
}
